<template>
  <ActionPanel :loading="loading">
    <div>
      <el-tree ref="treeRef" :data="data" show-checkbox node-key="value" :default-expanded-keys="value" :default-checked-keys="value" />
    </div>
    <template #footer>
      <div class="flex justify-center items-center">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="close">关闭</el-button>
      </div>
    </template>
  </ActionPanel>
</template>
<script setup lang="ts">
  import { ElTree, ElButton } from 'element-plus'
  import { closePopupKey } from '@/components/Popup'
  import { detailApi, setApi } from '@/seed-application/api'  
  import { ref, onMounted, inject } from 'vue'
  import feedback from '@/utils/feedback'
  import { Action } from '@/seed-application/types'
  import { getActions } from '@/seed-application'
  import { ActionPanel } from '@/components/ActionPanel'

  const props = defineProps<{action: Action, id: string}>()
  const action = props.action

  const treeRef = ref()
  const value = ref()
  const data = ref([])

  const close = inject<() => void>(closePopupKey, void 0)
  const loading = ref(false)
  const save = async () => {
    const checkedKeys = treeRef.value.getCheckedNodes().map(node => node.value).filter(v => v)
    loading.value = true
    await setApi(action, props.id, checkedKeys.join(','))
    feedback.msgSuccess(`${action.label}成功`)
    loading.value = false
    close?.()
  }

  onMounted(async () => {
    loading.value = true
    data.value = await getActions()
    value.value = await detailApi(action, props.id)
    loading.value = false
  })
</script>